﻿using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using mojoPortal.Web.RS.PRM.AppCode.Lib;

namespace mojoPortal.Web.RS.PRM.Controls
{
    public partial class EmployeeControl : RSBaseUserControl
    {
        
        protected void Page_Load(object sender, EventArgs e)
        {
            
            if (Request.QueryString["action"] == "edit")
            {
                btnEditEmployee.Visible = false;
                btnSaveEmployee.Visible = true;
            }
            if (Request.QueryString["action"] == "add")
            {
                btnEditEmployee.Visible = false;
                btnSaveEmployee.Visible = true;
            }
        }



        //private void LoadReportsToDDL(int companyid)
        //{
        //    SqlCommand myCommand;
        //    SqlDataReader myDataReader;
        //    String sqlSELECT = "SELECT e.EmployeeID, e.FirstName + ' ' + e.LastName AS FullName, e.CompanyId " +
        //                        "FROM rs_tblGroup g " +
        //                        "inner join rs_tblEmployee e " +
        //                        "on g.GroupId=e.GroupId " +
        //                        "WHERE e.CompanyId=@companyid and " +
        //                        "g.GroupName='CEO' and " +
        //                        "g.CompanyID=@companyid  " +
        //                        "ORDER BY e.FirstName ASC";
        //    SqlParameter param = new SqlParameter();
        //    SqlConnection myConnection;

        //    myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
        //    myCommand = new SqlCommand(sqlSELECT, myConnection);
        //    param.SqlDbType = SqlDbType.Int;
        //    param.ParameterName = "@companyid";
        //    param.Value = companyid;
        //    myCommand.Parameters.Add(param);
        //    myConnection.Open();
        //    myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
        //    ddlReportsTo.Items.Clear();
        //    ddlReportsTo.DataSource = myDataReader;
        //    ddlReportsTo.DataTextField = "FullName";
        //    ddlReportsTo.DataValueField = "EmployeeID";
        //    ddlReportsTo.DataBind();
        //    ddlReportsTo.Items.Insert(0, new ListItem("< Please select >", "0"));
        //    myConnection.Close();
        //}
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            string prevurl = string.Empty;
            if (Session["PreviousURL"] != null)
                prevurl = Session["PreviousURL"].ToString();
            else
                prevurl = Request.UrlReferrer.ToString();
            Response.Redirect(prevurl);
        }
        protected void btnEditEmployee_Click(object sender, EventArgs e)
        {
            int reportsto = hfReportsTo.Value == "" ? 0 : int.Parse(hfReportsTo.Value);
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite && userIdentity.RSEmployeeId == reportsto)
            {
                SetControlEnabledState(true);
                btnEditEmployee.Visible = false;
                btnSaveEmployee.Visible = true;
            }
            else
                ucModalActionMessageControl.ShowModal("You Do Not Have Permission To Perform This Action!", "", false);
        }
        protected void btnDeleteEmployee_Click(object sender, EventArgs e)
        {
            int reportsto = hfReportsTo.Value == "" ? 0 : int.Parse(hfReportsTo.Value);
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (reportsto == userIdentity.RSEmployeeId)
            {

            }
            else
                ucModalActionMessageControl.ShowModal("You Do Not Have Permission To Perform This Action!", "", false);

        }
        public void SetControlEnabledState(bool bstate)
        {
            RSPRMCommonFunctions.SetControlsEnabledState(this, bstate);
        }
        public bool LoadEmployeeData(int companyid, int Employeeid)
        {
            bool bHasValue = false;
            
            String strSQL = "select * from rs_tblEmployee where EmployeeID=@EmployeeID and companyid=@companyid";
            SqlCommand myCommand;
            SqlParameter param;
            SqlConnection myConnection;
            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(strSQL, myConnection);
            SqlDataReader myDataReader;

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@EmployeeID";
            param.Value = Employeeid;
            myCommand.Parameters.Add(param);

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);

            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            if (myDataReader.HasRows)
            {
                myDataReader.Read();
                txtEmployeeID.Text = Employeeid.ToString();

                txtFirstName.Text = myDataReader["FirstName"].ToString();
                txtMiddleName.Text = myDataReader["MiddleName"].ToString();
                txtLastName.Text = myDataReader["LastName"].ToString();
                txtEmail.Text = myDataReader["Email"].ToString();
                txtHomePhone.Text = myDataReader["HomePhone"].ToString();
                txtCellPhone.Text = myDataReader["CellPhone"].ToString();
                txtStreet.Text = myDataReader["Street"].ToString();
                txtCity.Text = myDataReader["City"].ToString();
                txtState.Text = myDataReader["State"].ToString();
                txtCountry.Text = myDataReader["Country"].ToString();
                txtPostalCode.Text = myDataReader["PostalCode"].ToString();

                if (myDataReader["ReportsTo"] != DBNull.Value)
                {
                    int reportsto = Convert.ToInt32(myDataReader["ReportsTo"].ToString());
                    txtReportsTo.Text = RSPRMCommonFunctions.GetEmployeeNameByID(companyid, reportsto);
                    hfReportsTo.Value = reportsto.ToString();
                }
                if (myDataReader["isLicensed"] != DBNull.Value)
                {
                    bool isLicensed = Convert.ToBoolean(myDataReader["isLicensed"]);
                    chkIsLicensed.Checked = isLicensed;
                }

                if (myDataReader["HireDate"] != DBNull.Value)
                {
                    DateTime hiredt = Convert.ToDateTime(myDataReader["HireDate"]);
                    txtHireDate.Text = hiredt.ToShortDateString();
                }

                if (myDataReader["BirthDate"] != DBNull.Value)
                {
                    DateTime birthdt = Convert.ToDateTime(myDataReader["BirthDate"]);
                    txtBirthDate.Text = birthdt.ToShortDateString();
                }

                txtNote.Text = myDataReader["Note"].ToString();
                txtTitle.Text = myDataReader["Title"].ToString();
                txtTitleOfCourtesy.Text = myDataReader["TitleOfCourtesy"].ToString();

                if (myDataReader["PhotoPath"] != DBNull.Value)
                {
                    imgEmployeePhoto.ImageUrl = myDataReader["PhotoPath"].ToString();
                }

                btnEditEmployee.Visible = true;
                bHasValue = true;

                if (Request.QueryString["action"] == "edit")
                { ; }
                else
                {
                    btnEditEmployee.Visible = true;
                    SetControlEnabledState(false);
                }
            }
            else
            {
                RSUserIdentity userIdentity = GetRSUserIdentity();
                txtReportsTo.Text = RSPRMCommonFunctions.GetEmployeeNameByID(userIdentity.RSCompanyId, userIdentity.RSEmployeeId);
                hfReportsTo.Value = userIdentity.RSEmployeeId.ToString();
            }

            myConnection.Close();
            return bHasValue;
        }

        protected void btnSaveEmployee_Click(object sender, EventArgs e)
        {
            string FirstName = "";
            string MiddleName = "";
            string LastName = "";
            string Email = "";
            string HomePhone = "";
            string CellPhone = "";
            string Street = "";
            string City = "";
            string State = "";
            string Country = "";
            string PostalCode = "";
            string HireDate = "";
            string BirthDate = "";
            string Note = "";
            string Title = "";
            string TitleOfCourtesy = "";
            bool isLicensed = false;
            int ReportsTo = 0;
            int EmployeeID = 0;
            RSUserIdentity userIdentity = GetRSUserIdentity();
            if (userIdentity.RSCanWrite)
            {
                int CompanyId = userIdentity.RSCompanyId;
                isLicensed = chkIsLicensed.Checked;
                FirstName = txtFirstName.Text.Trim();
                MiddleName = txtMiddleName.Text.Trim();
                LastName = txtLastName.Text.Trim();
                Email = txtEmail.Text.Trim();
                HomePhone = txtHomePhone.Text.Trim();
                CellPhone = txtCellPhone.Text.Trim();
                Street = txtStreet.Text.Trim();
                City = txtCity.Text.Trim();
                State = txtState.Text.Trim();
                Country = txtCountry.Text.Trim();
                PostalCode = txtPostalCode.Text.Trim();
                HireDate = txtHireDate.Text.Trim();
                BirthDate = txtBirthDate.Text.Trim();
                Note = txtNote.Text.Trim();
                Title = txtTitle.Text.Trim();
                TitleOfCourtesy = txtTitleOfCourtesy.Text.Trim();
                ReportsTo = Convert.ToInt32(hfReportsTo.Value);
                EmployeeID = txtEmployeeID.Text == "" ? 0 : Convert.ToInt32(txtEmployeeID.Text);

                SqlCommand sqlCmd = new SqlCommand();

                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@FirstName", SqlDbType.NVarChar, 30, ParameterDirection.Input, FirstName);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@MiddleName", SqlDbType.NVarChar, 30, ParameterDirection.Input, MiddleName);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@LastName", SqlDbType.NVarChar, 30, ParameterDirection.Input, LastName);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Email", SqlDbType.NVarChar, 50, ParameterDirection.Input, Email);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@HomePhone", SqlDbType.NVarChar, 15, ParameterDirection.Input, HomePhone);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CellPhone", SqlDbType.NVarChar, 15, ParameterDirection.Input, CellPhone);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Street", SqlDbType.NVarChar, 100, ParameterDirection.Input, Street);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@City", SqlDbType.NVarChar, 50, ParameterDirection.Input, City);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@State", SqlDbType.NVarChar, 50, ParameterDirection.Input, State);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Country", SqlDbType.NVarChar, 50, ParameterDirection.Input, Country);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@PostalCode", SqlDbType.NVarChar, 10, ParameterDirection.Input, PostalCode);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@HireDate", SqlDbType.NVarChar, 15, ParameterDirection.Input, HireDate);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@BirthDate", SqlDbType.NVarChar, 15, ParameterDirection.Input, BirthDate);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Note", SqlDbType.NVarChar, -1, ParameterDirection.Input, Note);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@Title", SqlDbType.NVarChar, 30, ParameterDirection.Input, Title);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@TitleOfCourtesy", SqlDbType.NVarChar, 25, ParameterDirection.Input, TitleOfCourtesy);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReportsTo", SqlDbType.Int, 0, ParameterDirection.Input, ReportsTo);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@EmployeeID", SqlDbType.Int, 0, ParameterDirection.Input, EmployeeID);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@isLicensed", SqlDbType.Bit, 0, ParameterDirection.Input, isLicensed);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);
                SQLHelper.AddParamToSQLCmd(sqlCmd, "@CurrentUser", SqlDbType.NVarChar, 25, ParameterDirection.Input, userIdentity.RSCurrentUser);
                SQLHelper.SetCommandType(sqlCmd, CommandType.StoredProcedure, "rs_uspSaveEmployee");
                SQLHelper.ExecuteScalarCmd(sqlCmd);

                int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
                if (returnValue > 0)
                {
                    if (FileUpload1.HasFile)
                    {
                        string folder = userIdentity.RSPhotoPath;
                        string fileLocalPath = Server.MapPath(folder);
                        string photoname = FileUpload1.FileName.Replace(" ", "_");
                        string photopath = folder + returnValue + "_" + photoname;
                        string filename_localpath = fileLocalPath + returnValue + "_" + photoname;
                        FileUpload1.SaveAs(filename_localpath);

                        EmployeeID = returnValue;
                        string SQL = "UPDATE rs_tblEmployee SET PhotoName=@PhotoName, PhotoPath=@PhotoPath WHERE EmployeeID=@EmployeeId AND CompanyID=@CompanyId";
                        sqlCmd = new SqlCommand();
                        SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
                        SQLHelper.AddParamToSQLCmd(sqlCmd, "@PhotoName", SqlDbType.NVarChar, 50, ParameterDirection.Input, photoname);
                        SQLHelper.AddParamToSQLCmd(sqlCmd, "@PhotoPath", SqlDbType.NVarChar, 255, ParameterDirection.Input, photopath);
                        SQLHelper.AddParamToSQLCmd(sqlCmd, "@EmployeeID", SqlDbType.Int, 0, ParameterDirection.Input, EmployeeID);
                        SQLHelper.AddParamToSQLCmd(sqlCmd, "@CompanyId", SqlDbType.Int, 0, ParameterDirection.Input, CompanyId);
                        SQLHelper.SetCommandType(sqlCmd, CommandType.Text, SQL);
                        SQLHelper.ExecuteScalarCmd(sqlCmd);
                    }

                    string prevurl = string.Empty;
                    if (Session["PreviousURL"] != null)
                        prevurl = Session["PreviousURL"].ToString();
                    else
                        prevurl = Request.UrlReferrer.ToString();
                    ucModalActionMessageControl.ShowModal("Employee Successfully Saved!", prevurl, true);
                    btnSaveEmployee.Enabled = false;
                }
            }
            else
                ucModalActionMessageControl.ShowModal("You Do Not Have Permission To Perform This Action!", "", false);
        }



    }
}